package cn.tedu._05weibo.common.exception;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import springfox.documentation.spring.web.json.Json;

import javax.validation.ConstraintViolationException;

/*
*   @ControllerAdvice
*       1.将次类标识为全局异常处理器的类
* */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandle(ConstraintViolationException ex){
        String message = ex.getMessage().split(":")[1].trim();
        log.error("验证框架抛出异常: "+ message);

        return new JsonResult(StatusCode.VALIDATE_ERROR,message);
    }

    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException
            (MethodArgumentNotValidException ex){
//        DTO类方式进行消息效验 --> 针对于 @Validated注解
        String message = ex.getFieldError().getDefaultMessage();
        log.error("message = "+ message);

        return new JsonResult(StatusCode.VALIDATE_ERROR,message);
    }

    /**
    *   @ExceptionHandler 标识此方法为异常处理方法
     *  @ResponseBody 返回给前端要添加这个注解.否则浏览器不接收数据
    * */
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        log.error("ex = "+ ex.getMessage());

        /*
        *   state : 2002
        *   message: 操作失败
        *   data: ID值不能小于0
        * */
        return new JsonResult(StatusCode.OPERATION_FAILED,ex.getMessage());
    }

    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        log.error("RuntimeException = "+ex.getMessage());

        return new JsonResult(StatusCode.OPERATION_FAILED,ex.getMessage());
    }

//    能够处理所有由处理器抛出的异常
//    @ExceptionHandler
//    public JsonResult doThrowableException(Throwable ex){
//        log.error("Throwable = "+ ex.getMessage());
//
//        return new JsonResult(StatusCode.THROWABLE_ERRPR,ex.getMessage());
//    }


}

